package com.cscec.omega.utils;

import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class RequestUtil {

    /**
     * 将request中的Mep转换成map
     */
    public static Map<String, Object> request2Map(HttpServletRequest request){
        Map<String, Object> map = null;
        try {
            if(request.getParameterMap()!=null && request.getParameterMap().size()!=0){
                Map<String, Object> mapItem = new HashMap<>();
                request.getParameterMap().forEach((key, value) -> mapItem.put(key, value[0]));
                map = mapItem;
            }else {
                map = getRequestPostStr(request);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * json转换成map
     * @param request
     * @return
     * @throws IOException
     */
    private static Map<String,Object> getRequestPostStr(HttpServletRequest request)
            throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        Map<String, Object> map = (Map) JSON.parse(new String(buffer, charEncoding));
        return map;
    }

    private static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if(contentLength<0){
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength;) {

            int readLen = request.getInputStream().read(buffer, i,
                    contentLength - i);
            if (readLen == -1) {
                break;
            }
            i += readLen;
        }
        return buffer;
    }
}
